import {orderApi} from "@/api.js";
import {Iap} from "@/libs/iap.js";
import store from "@/store";

const channels = [
  {
    label: '微信支付',
    code: 'wxpay',
  },
  {
    label: '支付宝',
    code: 'alipay',
  },
  {
    label: '抖音支付',
    code: 'toutiao',
  },
  {
    label: '苹果支付',
    code: 'appleiap'
  },
]
let iapInstance;
export default {
  _locked: false,
  async init() {
    this._locked = false
    let {providers, provider} = await _getProvider()
    channels.map(channel => {
      let found
      // #ifdef APP-PLUS
      found = providers.find(item => item.id === channel.code)
      // #endif
      // #ifdef MP
      found = provider.find(item => item === channel.code)
      // #endif

      if (found) {
        channel.provider = found
        channel.installed = true
      }
    })
  },

  getChannels({needVirtual = false, debug = false}) {
    // return {
    //   channels: [],1
    //   channel: null
    // }
    // ios审核时，虚拟产品使用苹果支付1
    if (store.getters.review && needVirtual && store.getters.os === 'ios') {
      let found
      // #ifdef APP-PLUS
      found = channels.find(channel => channel.provider && channel.code === 'appleiap')
      // #endif

      // #ifdef MP-TOUTIAO
      found = channels.find(channel => channel.provider && channel.code === 'toutiao')
      if (found)
        found.message = 'iOS暂不支持购买'
      // #endif

      // #ifdef MP-WEIXIN
      found = channels.find(channel => channel.provider && channel.code === 'wxpay')
      if (found)
        found.message = 'iOS暂不支持购买'
      // #endif
      if (found) {
        const {code, label, message} = found
        const channel = {
          code, label, message
        }
        return {
          channels: [channel],
          channel: channel
        }
      }

      return {
        channels: [],
        channel: null
      }
    }

    const list = []
    channels.find(channel => {
      let {code, label, disable, installed} = channel

      if (disable || !installed) {
        if (!debug) {
          return
        }
      }

      list.push({
        code, label, disable
      })
    })

    const res = {}
    res.channels = list
    const found = res.channels.find(channel => !channel.disable)
    if (found) {
      res.channel = found
    } else {
      res.channel = null
    }
    return res
  },

  getChannel(channelCode) {
    return channels.find(item => item.code === channelCode)
  },

  async toPay({channelCode, mode, order, product}) {
    if (this._locked) {
      console.log('支付中...')
      throw new Error()
    }

    this._locked = true
    uni.showLoading({
      title: '下单中...',
      mask: true
    })

    let params, orderId
    try {
      let res
      await this.preRequestPayment(channelCode, product)

      if (mode === 'order') {
        res = await orderApi.payOrder(channelCode, order.id)
      } else {
        res = await orderApi.buy(channelCode, product.id)
      }
      params = res.data.data.params;
      orderId = res.data.data.orderId;
      uni.hideLoading()
      if (channelCode === 'test') {
        return orderId
      }


      // orderId = 'xx' + Date.now()
      //
      // params = {
      //   "orderInfo": {
      //     "productid": "member_six",
      //     "manualFinishTransaction": true,
      //     "username": orderId
      //   }
      // }

      res = await _requestPayment(channelCode, params)

      await this.postRequestPayment(channelCode, orderId, res)
    } catch (e) {
      this._locked = false
      throw e
    }

    return orderId
  },

  async preRequestPayment(channelCode, product) {
    if (channelCode === 'appleiap') {
      await this.appleIapPreRequestPayment(product)
    }
  },

  async postRequestPayment(channelCode, orderId, result) {
    if (channelCode === 'appleiap') {
      await this.appleIapPostRequestPayment(orderId, result)
    }
  },

  async appleIapPostRequestPayment(orderId, transaction) {
    await orderApi.appResultUpload(transaction.transactionReceipt, orderId)
  },
  async appleIapPreRequestPayment(product) {
    if (!iapInstance) {
      const channel = this.getChannel('appleiap')
      console.log('channel', channel)
      iapInstance = new Iap(channel.provider)
    }

    try {
      await iapInstance.getProduct([product.iosProductId])
      // console.log(transactions)
    } catch (e) {
      console.log(e)
      throw new Error('ios内购失败')
    }
  }
}


function _getProvider() {
  return new Promise(resolve => {
    uni.getProvider({
      service: "payment",
      success: (res) => {
        console.log('payment', res)
        resolve(res)
      }
    })
  })
}

function _requestPayment(provider, params) {
  console.log('_requestPayment', provider, params)
  return new Promise((resolve, reject) => {
    uni.requestPayment({
      provider,
      ...params,
      success: (paymentRes) => {
        console.log('支付成功客户端回调', paymentRes)

        // #ifdef MP-TOUTIAO
        if (paymentRes.code !== 0) {
          reject(new Error('已取消.'))
          return
        }
        // #endif
        resolve(paymentRes)
      },
      fail: (e) => {
        console.log(e)
        reject(e)
      },
      complete: () => {
        reject()
      }
    })
  })
}
